package com.lahuan.config.datasouce;


import com.lahuan.config.datasouce.entity.GlobalXid;
import com.lahuan.config.datasouce.entity.XaBranch;

import java.util.HashSet;

/**
 * @author lfy
 */
public class XaTransactionHolder {

    /**
     * 当前线程的事务的xid
     */
    private static final ThreadLocal<GlobalXid> globalXidHolder = new ThreadLocal<>();
    /**
     * 当前线程一共用到的分支
     */
    private static final ThreadLocal<HashSet<XaBranch>> xaBranchSetHolder = new ThreadLocal<>();
    /**
     * 当前在用的分支
     */
    private static final ThreadLocal<XaBranch> currentXaBranchHolder = new ThreadLocal<>();

    protected static void clear(){
        globalXidHolder.remove();
        xaBranchSetHolder.remove();
        currentXaBranchHolder.remove();
    }

    public static GlobalXid getGlobalXid() {
        return globalXidHolder.get();
    }

    public static void setGlobalXid(GlobalXid globalXid) {
        globalXidHolder.set(globalXid);
    }

    public static HashSet<XaBranch> getXaBranchSet() {
        return xaBranchSetHolder.get();
    }

    public static void addXaBranchSet(XaBranch xaBranch) {
        HashSet<XaBranch> set = xaBranchSetHolder.get();
        if(set ==null){
            set = new HashSet<>();
            xaBranchSetHolder.set(set);
        }
        set.add(xaBranch);
    }

    public static XaBranch getCurrentXaBranch() {
        return currentXaBranchHolder.get();
    }

    public static void setCurrentXaBranchHolder(XaBranch xaBranch) {
        currentXaBranchHolder.set(xaBranch);
    }
}
